﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace BullShitPoker
{
    public partial class MainWindow : Form
    {

        public string name;
        int second = 0;
        string lastMove;
        string move;
        public delegate void Make(string s);
        public delegate void Start();
        public Start sRound;
        public Start sStopGame;
        public Start sCleanChat;
        public Make mChat;
        public Make mNextMove;
        private StartScreen StartWindow;

        public MainWindow(string name, StartScreen start)
        {
            InitializeComponent();
            this.name = name;
            Worker.form = this;
            string text = Client.Sender("a\nChat");
            RenewChat(text);
            mChat = new Make(RenewChat);
            mNextMove = new Make(NextMove);
            sRound = new Start(StartRound);
            sStopGame = new Start(StopGame);
            sCleanChat = new Start(ClearChat);
            if (Client.Sender(name + "\nRoundStarted") == "True") StartRound();
            StartWindow = start;
        }

        private void step_Tick(object sender, EventArgs e)
        {
            Counter.Text = second.ToString();
            second--;
        }
                
        private void loadCards(string s)
        {
            if (s.Length < 3) return;
            string[] cards = s.Split('|');
            List<Bitmap> image = new List<Bitmap>();
            for (int i = 0; i < cards.Length; i++)
            {
                string[] tmp = cards[i].Split(',');
                image.Add((Bitmap)global::BullShitPoker.Properties.Resources.ResourceManager.GetObject(
                    "_" + (Int32.Parse(tmp[0]) + 2).ToString() + "_" + (Int32.Parse(tmp[1]) + 1).ToString()));
            }
            if (cards.Length == 3)
            {
                card1.Visible = true;
                card1_box.Image = image[0];
                card2.Visible = true;
                card2_box.Image = image[1];
                card3.Visible = true;
                card3_box.Image = image[2];
            }
            if (cards.Length == 2)
            {
                card1.Visible = true;
                card1_box.Image = image[0];
                card2.Visible = true;
                card2_box.Image = image[1];
                card3.Visible = false;
            }
            if (cards.Length == 1)
            {
                card1.Visible = true;
                card1_box.Image = image[0];
                card2.Visible = false;
                card3.Visible = false;
            }
        }

        private void tenSecond_Tick(object sender, EventArgs e)
        {
            No.PerformClick();
        }

        private void No_Click(object sender, EventArgs e)
        {
            step.Enabled = false;
            tenSecond.Enabled = false;
            Counter.Text = "";
            Client.Sender(name + "\nNo " + name);
        }

        private void unblock()
        {
            No.Enabled = true;
            lastMove = Client.Sender(name + "\nLastMove");
            int type;
            selectCardBox.Enabled = false;
            selectSuitBox.Enabled = false;
            selectTypeBox.Items.Clear();
            selectTypeBox.Enabled = true;
            try
            {
                type = Int32.Parse(lastMove.Split('|')[1]);
            }
            catch { type = 0; }
            for (int i = type; i < Worker.Types.Length; i++)
            {
                selectTypeBox.Items.Add(Worker.Types[i]);
            }
        }

        private void StartRound()
        {
            Ok.Enabled = false;
            No.Enabled = false;
            card1.Visible = false;
            card2.Visible = false;
            card3.Visible = false;
            selectTypeBox.Enabled = false;
            selectCardBox.Enabled = false;
            selectSuitBox.Enabled = false;
            loadCards(Client.Sender(name + "\nMyCards " + name));
            NextMove(Client.Sender(name + "\nNextPlayer"));
            RoundText.Text = "Round #" + Client.Sender(name + "\nRound");
            TotalCards.Text = "Total Cards " + Client.Sender(name + "\nCountAll");
        }
        private void RenewChat(string s)
        {
            TXTArea.Text += '\n' + s;
            DeleteN();
            PlayerComments(s);
            TXTArea.SelectionStart = TXTArea.Text.Length - 1;
        }
        private void DeleteN()
        {
            TXTArea.Text = TXTArea.Text.Trim();
            TXTArea.Text = TXTArea.Text.Replace("\n\n", "\n");
        }
        private void PlayerComments(string s)
        {
        }


        private void NextMove(string player)
        {
            if (player == name)
            {
                unblock();
                if (!tenSecond.Enabled) tenSecond.Enabled = true;
                if (!step.Enabled)
                {
                    second = 60;
                    step.Enabled = true;
                }
            }
        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            Client.Sender(name + "\nRemove " + name);
            Client.Close();
            StartWindow.Show();
            this.Dispose();
        }


        internal void Invoke(MethodInvoker methodInvoker)
        {
            throw new NotImplementedException();
        }

        private void selectTypeBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectSuitBox.Enabled = false;
            selectCardBox.Enabled = false;
            Ok.Enabled = false;
            selectCardBox.Items.Clear();
            selectSuitBox.Items.Clear();
            if (selectTypeBox.SelectedItem.ToString() != Worker.Types[4] &&
                selectTypeBox.SelectedItem.ToString() != Worker.Types[9] &&
                selectTypeBox.SelectedItem.ToString() != Worker.Types[8])
            {
                selectCardBox.Enabled = true;
                int card = 1;
                try
                {
                    if (Worker.Types[Int32.Parse(lastMove.Split('|')[1])] == selectTypeBox.SelectedItem.ToString())
                    {
                        card = Int32.Parse(lastMove.Split('|')[2]) + 1;
                        if (selectTypeBox.SelectedItem.ToString() == Worker.Types[2] ||
                        selectTypeBox.SelectedItem.ToString() == Worker.Types[6]) card--;
                    }
                }
                catch { card = 1; }
                for (int i = card; i < Worker.Cards.Length; i++)
                {
                    selectCardBox.Items.Add(Worker.Cards[i]);
                }
            } 
            else 
            {
                selectSuitBox.Enabled = true;
                int suit = 0;
                try
                {
                    if (Worker.Types[Int32.Parse(lastMove.Split('|')[1])] == selectTypeBox.SelectedItem.ToString())
                         suit = Int32.Parse(lastMove.Split('|')[3]) + 1;
                }
                catch { suit = 0; }
                for (int i = suit; i < Worker.Suits.Length; i++)
                {
                    selectSuitBox.Items.Add(Worker.Suits[i]);
                }
            }
        }

        private void selectCardBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string type;
            try
            {
                type = selectTypeBox.SelectedItem.ToString();
            }
            catch
            {
                return;
            }
            if (type == Worker.Types[0] || type == Worker.Types[1] || type == Worker.Types[3] ||
                type == Worker.Types[5] || type == Worker.Types[7] || type == Worker.Types[10] ||
                type == Worker.Types[11] || type == Worker.Types[12] || type == Worker.Types[13])
            {
                move = Worker.Types.ToList().IndexOf(type) + "|" + 
                    Worker.Cards.ToList().IndexOf(selectCardBox.SelectedItem.ToString()) + "|0";
                Ok.Enabled = true;
            }
            else if (type == Worker.Types[2] || type == Worker.Types[6])
            {
                selectSuitBox.Items.Clear();
                selectSuitBox.Enabled = true;
                int card = 1;
                try
                {
                    if (Worker.Types[Int32.Parse(lastMove.Split('|')[1])] == selectTypeBox.SelectedItem.ToString())
                    {
                        card = Int32.Parse(lastMove.Split('|')[3]);
                        if (selectCardBox.SelectedItem.ToString() == Worker.Cards[Int32.Parse(lastMove.Split('|')[2])])
                           card++;
                    }
                }
                catch { card = 1; }
                for (int i = card; i < Worker.Cards.Length; i++)
                {
                    if (i == Worker.Cards.ToList().IndexOf(selectCardBox.SelectedItem.ToString())) continue;
                    selectSuitBox.Items.Add(Worker.Cards[i]);
                }
            }
            else if (type == Worker.Types[8])
            {
                move = Worker.Types.ToList().IndexOf(type) + "|" + 
                    Worker.Cards.ToList().IndexOf(selectCardBox.SelectedItem.ToString())
                    + "|" + Worker.Suits.ToList().IndexOf(selectSuitBox.SelectedItem.ToString());
                Ok.Enabled = true;
            }
        }

        private void selectSuitBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string type;
            try
            {
                type = selectTypeBox.SelectedItem.ToString();
            }
            catch
            {
                return;
            }
            if (type == Worker.Types[4] || type == Worker.Types[9])
            {
                move = Worker.Types.ToList().IndexOf(type) + "|1|" 
                    + Worker.Suits.ToList().IndexOf(selectSuitBox.SelectedItem.ToString());
                Ok.Enabled = true;
            }
            else if (type == Worker.Types[8])
            {
                selectCardBox.Items.Clear();
                selectCardBox.Enabled = true;
                int card = 1;
                try
                {
                    if (Worker.Types[Int32.Parse(lastMove.Split('|')[1])] == type)
                        card = Int32.Parse(lastMove.Split('|')[2]) + 1;                    
                }
                catch { card = 1; }
                for (int i = card; i < Worker.Cards.Length; i++)
                {
                    selectCardBox.Items.Add(Worker.Cards[i]);
                }
            }
            else
            {
                move = Worker.Types.ToList().IndexOf(type) + "|" + 
                    Worker.Cards.ToList().IndexOf(selectCardBox.SelectedItem.ToString())
                    + "|" + Worker.Cards.ToList().IndexOf(selectSuitBox.SelectedItem.ToString());
                Ok.Enabled = true;
            }
        }

        private void Ok_Click(object sender, EventArgs e)
        {
            Worker.SendMove(move);
            selectCardBox.Enabled = false;
            selectTypeBox.Enabled = false;
            selectSuitBox.Enabled = false;
            Ok.Enabled = false;
            No.Enabled = false;
            tenSecond.Enabled = false;
            step.Enabled = false;
            Counter.Text = "";
        }

        private void StopGame()
        {
            var a = MessageBox.Show("Game has finished. Do you wanna play more (Yes) or wanna exit (No)?",
                "Game's finished", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (a == DialogResult.No)
            {
                StartWindow.Show();
                this.Dispose();
                return;
            }
            step.Enabled = false;
            No.Enabled = false;
            Ok.Enabled = false;
            selectCardBox.Enabled = false;
            selectTypeBox.Enabled = false;
            selectSuitBox.Enabled = false;
            Counter.Text = "";
            string response = Client.Sender("a\nRegister " + name);
            if (response != "True")
            {
                StartWindow.Show();
                this.Dispose();
                return;
            }
        }

        private void SendButton_Click(object sender, EventArgs e)
        {
            string text = SayBox.Text;
            if (text.Length > 0) Client.Sender(name + "\nSay " + text);
            SayBox.Text = "";
            SayBox.Focus();
        }

        private void SayBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar.Equals((char)Keys.Enter)) SendButton.PerformClick(); 
        }

        private void ClearChat()
        {
            TXTArea.Text = "";
        }


    }    
}
